package com.dmooo.ymx.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dmooo.ymx.R;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.PddClient;
import com.dmooo.ymx.common.CommonUtils;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.common.T;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class HuZhuanActivity extends BaseActivity {
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.huzhuan_yuenum)
    TextView huzhuanYuenum;
    @BindView(R.id.huzhuan_phone)
    EditText huzhuanPhone;
    @BindView(R.id.huzhuan_agphone)
    EditText huzhuanAgphone;
    @BindView(R.id.huzhuan_jenum)
    EditText huzhuanJenum;
    @BindView(R.id.huzhuan_agjenum)
    EditText huzhuanAgjenum;
    @BindView(R.id.huzhuan_zfmm)
    EditText huzhuanZfmm;
    @BindView(R.id.huzhuan_content)
    EditText huzhuanContent;
    @BindView(R.id.huzhuan_yzm)
    EditText huzhuanYzm;
    @BindView(R.id.huzhuan_sendyzm)
    TextView huzhuanSendyzm;
    private TimeCount time;
    @Override
    protected void initUI() {
        setContentView(R.layout.activity_huzhuan);
        ButterKnife.bind(this);
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("金币互转");
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("互转记录");
        huzhuanSendyzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendyzm();
            }
        });
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle=new Bundle();
                bundle.putInt("type",3);
                openActivity(HuzhuanListDetailActivity.class,bundle);
            }
        });
    }

    @Override
    protected void initData() {
        time = new TimeCount(60000, 1000);
        huzhuanYuenum.setText(getIntent().getExtras().getString("money"));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initListener() {

    }
    private void sendyzm() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }

        RequestParams params = new RequestParams();
        params.put("phone", SPUtils.getStringData(this,"phone",""));
        // get方式
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Sms&a=sendPay", params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String responseResult = new String(arg2);
                LogUtils.e(TAG, "onSuccess()--" + responseResult);
                try {
                    JSONObject jsonObject = new JSONObject(responseResult);
                    String code = jsonObject.optString("code");
                    String msg = jsonObject.optString("msg");
                    // String result = jsonObject.optString("result");
                    if ("0".equalsIgnoreCase(code)) { // 操作成功
                        time.start();
                        showToast(getResources().getString(R.string.get_verification_code_success));
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    LogUtils.i(TAG, e.toString());
                }
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + arg3.toString());
            }
        });
    }
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            huzhuanSendyzm.setClickable(false);
            huzhuanSendyzm.setText("倒计时" + millisUntilFinished / 1000 + getResources().getString(R.string.seconds_after));
            // btn_get_code.setTextSize(15);
//            btn_code.setTextColor(getResources().getColor(R.color.col_999));
//            btn_code.setBackground(getResources().getDrawable(R.drawable.bg_border_gray));
        }

        @SuppressLint("NewApi")
        @Override
        public void onFinish() {// 计时完毕时触发
            huzhuanSendyzm.setText(getResources().getString(R.string.get_verification_code));
            huzhuanSendyzm.setClickable(true);
        }

    }
    @OnClick({R.id.tv_left, R.id.huzhuan_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.huzhuan_button:
                if (TextUtils.isEmpty(huzhuanPhone.getText().toString())) {
                    T.showShort(this, "请输入收款账号");
                    return;
                }
                if (TextUtils.isEmpty(huzhuanAgphone.getText().toString())) {
                    T.showShort(this, "请确认收款账号");
                    return;
                }
                if (TextUtils.isEmpty(huzhuanJenum.getText().toString())) {
                    T.showShort(this, "请输入互转金额");
                    return;
                }
                if (TextUtils.isEmpty(huzhuanAgjenum.getText().toString())) {
                    T.showShort(this, "请确认金额");
                    return;
                }
//                if (TextUtils.isEmpty(huzhuanZfmm.getText().toString())) {
//                    T.showShort(this, "请输入支付密码");
//                    return;
//                }
                //绑定操作
                AlertDialog.Builder builder = new AlertDialog.Builder(HuZhuanActivity.this);
                builder.setTitle("嗨车宝");
                builder.setMessage("确定进行余额互转操作吗，互转成功后不可撤回。");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定互转", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        huzhuan();
                        dialog.dismiss();
                    }
                });
                builder.show();
                break;
        }
    }

    private void huzhuan() {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        RequestParams requestParams = new RequestParams();
        requestParams.put("data_type", PddClient.data_type);
        requestParams.put("version_sign", PddClient.version);
        requestParams.put("timestamp", time);
        requestParams.put("token", SPUtils.getStringData(this, "token", ""));
        requestParams.put("type", "yxm.UserBalanceRecord.transfer");
        requestParams.put("account", huzhuanPhone.getText().toString().trim());
//        requestParams.put("repeat_account", huzhuanAgphone.getText().toString().trim());
        requestParams.put("money", huzhuanJenum.getText().toString().trim());
//        requestParams.put("draw_pwd", huzhuanZfmm.getText().toString().trim());
        requestParams.put("remark", huzhuanContent.getText().toString().trim());
//        requestParams.put("repeat_money", huzhuanAgjenum.getText().toString().trim());
        requestParams.put("code",huzhuanYzm.getText().toString());
        Map<String, String> temp = new HashMap<>();
        temp.put("data_type", PddClient.data_type);
        temp.put("version_sign", PddClient.version);
        temp.put("timestamp", time);
        temp.put("token", SPUtils.getStringData(this, "token", ""));
        temp.put("type", "yxm.UserBalanceRecord.transfer");
        temp.put("account", huzhuanPhone.getText().toString().trim());
//        temp.put("repeat_account", huzhuanAgphone.getText().toString().trim());
        temp.put("money", huzhuanJenum.getText().toString().trim());
//        temp.put("draw_pwd", huzhuanZfmm.getText().toString().trim());
        temp.put("remark", huzhuanContent.getText().toString().trim());
//        temp.put("repeat_money", huzhuanAgjenum.getText().toString().trim());
        temp.put("code",huzhuanYzm.getText().toString());
        String sign = PddClient.getSign1(temp);
        requestParams.put("sign", sign);
        Log.d("DDDDDD",requestParams.toString());
        HttpUtils.post(Constants.APP_IP+"/app.php?c=UserBalanceRecord&a=transfer", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    int code = jsonObject.optInt("code");
                    String msg = jsonObject.optString("msg");
                    if (code == 0) {
                        showToast(msg);
                        finish();
                    } else {
                        showToast(msg);
                        if ("用户不存在".equals(msg)) {
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
